#!/bin/bash
# zimbrabackup.sh
# This script running zimbrabackup on a ZCS server. It also makes sure
# the script's dependencies are present.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

show_help ()
{
echo "Usage: 
     zimbrabackup -a 	
			Execute full backup, all accounts.
     zimbrabackup -a mail1,mail2,...,mailn
			Execute backup full for specific accounts.
     zimbrabackup -ldap 	
			Execute full backup, all accounts.
     zimbrabackup -ldap mail1,mail2,...,mailn
			Execute backup full for specific accounts.
     zimbrabackup -i 	
			Execute a full incremental backup all accounts.
			Needs a least one full backup of all account complete.
     zimbrabackup -i mail1,mail2,...,mailn	
			Execute a incremental backup in specified accounts provided in the command line.
			If the account doesn't have a previosly full backup, will be done in the same session.
     zimbrabackup --backupDistributionList
			Make full backup of Distribution  Lists
     zimbrabackup --backupAlias
			Make full backup of Alias
"
exit 0 
}

###### MAIN ############
#Specify Domain for backup all accounts.
DOMAIN='dc=domain,dc=com,dc=br'

# Here the code loads the config file
source /etc/zimbrabackup/zimbrabackup.conf

#
if ! [ -z "$BACKUPUSER" ]; then
	if [ "$(id -u)" != "$(id -u $BACKUPUSER)" ]; then
		echo "You need to be $BACKUPUSER to run this script"
		exit 0
	fi
else
	echo "You need to define the variable BACKUPUSER"
	exit 0
fi

if ! [ -z "$WORKDIR" ]; then
        if ! [ -d "$WORKDIR" ]; then
                echo "The directory $WORKDIR doesn't exist"
                exit 0
        fi
else
        echo "You need to define the variable WORKDIR"
        exit 0
fi

if [ -z "$ADMINUSER" ]; then
        echo "You need to define the variable ADMINUSER"
        exit 0
fi

if [ -z "$ADMINPASS" ]; then
        echo "You need to define the variable ADMINPASS"
        exit 0
fi

if [ -z "$LDAPMASTERSERVER" ]; then
        echo "You need to define the variable LDAPMASTERSERVER"
        exit 0
fi

if [ -z "$LDAPZIMBRADN" ]; then
        echo "You need to define the variable LDAPZIMBRADN"
        exit 0
fi

if [ -z "$LDAPZIMBRAPASS" ]; then
        echo "You need to define the variable LDAPZIMBRAPASS"
        exit 0
fi

if [ -z "$LOGFILE" ]; then
        echo "You need to define the variable LOGFILE"
        exit 0
fi

# Function to notify completes backup trough e-mail
notify_email()
{
	
	TIPO=$1;
	session=$2;
	du -h $WORKDIR/$session/* > /tmp/list-$session ;
	total=$(du -h $WORKDIR/$session | awk {'print $1'});
	(echo "Subject: Backup $TIPO completed on $(date)";echo "Backup $TIPO completed on $(date)";echo -e "\r\nTotal: $total ";echo "Summary of files:"; cat /tmp/list-$session) | /opt/zimbra/postfix/sbin/sendmail $EMAIL_NOTIFY
}

#Efetua backup full de todas as contas sequencialmente
#Make full backup of all accounts, sequential.
backup_all_accounts_per_domain ()
{
	LISTALLACCOUNTS=$(mktemp)
	$(which ldapsearch) -x -H $LDAPMASTERSERVER -D $LDAPZIMBRADN -w $LDAPZIMBRAPASS -b $DOMAIN -LLL "(objectclass=zimbraAccount)" zimbraMailDeliveryAddress zimbraMailHost | grep ^zimbraMail | awk '{print $2}' > "$LISTALLACCOUNTS"
	SESSION="full-"$(date  +%Y%m%d%H%M%S)
	echo "SESSION: $SESSION started on $(date)" >> $WORKDIR/sessions.txt
	TEMPDIR=$(mktemp -d $WORKDIR/XXXX)
	
	for MAIL in $(grep @ $LISTALLACCOUNTS); do
        	MAILHOST=$(grep -A1 ^$MAIL $LISTALLACCOUNTS| grep -v @)
	        $(which ldapsearch) -x -H $LDAPMASTERSERVER -D $LDAPZIMBRADN -w $LDAPZIMBRAPASS -b $DOMAIN -LLL "(zimbraMailDeliveryAddress=$MAIL)" > $TEMPDIR/$MAIL.ldiff
	        $(which curl) -k -u $ADMINUSER:$ADMINPASS https://$MAILHOST:7071/home/$MAIL/?fmt=tgz > $TEMPDIR/$MAIL.tgz
	        $(which curl) -k -u $ADMINUSER:$ADMINPASS https://$MAILHOST:7071/home/$MAIL/Junk?fmt=tgz > $TEMPDIR/$MAIL.Junk.tgz &
	        $(which curl) -k -u $ADMINUSER:$ADMINPASS https://$MAILHOST:7071/home/$MAIL/Trash?fmt=tgz > $TEMPDIR/$MAIL.Trash.tgz &
	        echo $SESSION:$MAIL:$(date +%m/%d/%y) >> $WORKDIR/sessions.txt
	done

	mv "$TEMPDIR" "$WORKDIR/$SESSION" && rm -rf "$TEMPDIR"
	echo "SESSION: $SESSION completed in $(date)" >> $WORKDIR/sessions.txt
	notify_email "FULL" $SESSION 

	exit 0
}
backup_accounts_per_domain ()
{
	
	
	if [ -z $SESSION ]; then
		SESSION="full-"$(date  +%Y%m%d%H%M%S)
	fi


        SUBSESSION="$SESSION"
        SUBTEMP=$TEMPDIR
	
	

        if [ -z $2 ]; then
                SESSION=$SUBSESSION
                CONTROLE=1
        else
                SESSION="full-"$(date  +%Y%m%d%H%M%S)
                CONTROLE=0
        fi

        echo "SESSION: $SESSION started on $(date)" >> $WORKDIR/sessions.txt
        TEMPDIR=$(mktemp -d $WORKDIR/XXXX)
	K=1

	while true; do

	        MAIL=$(echo $1, | cut -d, -f$K)

	        if [ -z $MAIL ]; then
	                break
	        fi

	        $(which ldapsearch) -x -H $LDAPMASTERSERVER -D $LDAPZIMBRADN -w $LDAPZIMBRAPASS -b $DOMAIN -LLL "(zimbraMailDeliveryAddress=$MAIL)" > $TEMPDIR/$MAIL.ldiff
	        MAILHOST=$(grep ^zimbraMailHost $TEMPDIR/$MAIL.ldiff | awk '{print $2}')
	        $(which curl) -k -u $ADMINUSER:$ADMINPASS https://$MAILHOST:7071/home/$MAIL/?fmt=tgz > $TEMPDIR/$MAIL.tgz
	        $(which curl) -k -u $ADMINUSER:$ADMINPASS https://$MAILHOST:7071/home/$MAIL/Junk?fmt=tgz > $TEMPDIR/$MAIL.Junk.tgz
	        $(which curl) -k -u $ADMINUSER:$ADMINPASS https://$MAILHOST:7071/home/$MAIL/Trash?fmt=tgz > $TEMPDIR/$MAIL.Trash.tgz
	        echo $SESSION:$MAIL:$(date +%m/%d/%y) >> $WORKDIR/sessions.txt
	        ((K = K+1))
	        unset MAIL
	        sleep 1
	done


        
        if [ -d "$WORKDIR/$SESSION/"  ]; then
                cp "$TEMPDIR/"* "$WORKDIR/$SESSION/" && rm -rf "$TEMPDIR"
        else
                mv "$TEMPDIR" "$WORKDIR/$SESSION" && rm -rf "$TEMPDIR"
        fi
        
	echo "SESSION: $SESSION concluída em $(date)" >> $WORKDIR/sessions.txt
	notify_email "FULL" $SESSION 
	SESSION="$SUBSESSION"
	TEMPDIR="$SUBTEMP"
}
#Make full backup ldap config of all accounts per domain, sequential.
backup_all_accounts_ldap_per_domain ()
{
	LISTALLACCOUNTS=$(mktemp)
	$(which ldapsearch) -x -H $LDAPMASTERSERVER -D $LDAPZIMBRADN -w $LDAPZIMBRAPASS -b $DOMAIN -LLL "(objectclass=zimbraAccount)" zimbraMailDeliveryAddress zimbraMailHost | grep ^zimbraMail | awk '{print $2}' > "$LISTALLACCOUNTS"
	SESSION="full-"$(date  +%Y%m%d%H%M%S)
	echo "SESSION: $SESSION started on $(date)" >> $WORKDIR/sessions.txt
	TEMPDIR=$(mktemp -d $WORKDIR/XXXX)
for MAIL in $(grep @ $LISTALLACCOUNTS); do
       	MAILHOST=$(grep -A1 ^$MAIL $LISTALLACCOUNTS| grep -v @)
        $(which ldapsearch) -x -H $LDAPMASTERSERVER -D $LDAPZIMBRADN -w $LDAPZIMBRAPASS -b $DOMAIN -LLL "(zimbraMailDeliveryAddress=$MAIL)" > $TEMPDIR/$MAIL.ldiff
echo $SESSION:$MAIL:$(date +%m/%d/%y) >> $WORKDIR/sessions.txt
	done

	mv "$TEMPDIR" "$WORKDIR/$SESSION" && rm -rf "$TEMPDIR"
	echo "SESSION: $SESSION completed in $(date)" >> $WORKDIR/sessions.txt
	notify_email "FULL" $SESSION 

	exit 0
}
# Criticize the parameters passed on the command line

case "$1" in
"-a" )
	if [ -z "$2" ]; then
		if [ $SEQUENTIAL_SUPPORT -eq 1  ];then
			echo "Running the sequential backup"
			backup_all_accounts_per_domain
		else
			backup_all_accounts_per_domain
		fi
	else
		if [ -z "$3" ]; then
			backup_accounts_per_domain $2
		else
			echo "Incorrect $@ params. Read --help."
			show_help
		fi
	fi

;;
case "$1" in
"-ldap" )
	if [ -z "$2" ]; then
		if [ $SEQUENTIAL_SUPPORT -eq 1  ];then
			echo "Running the sequential backup of ldap config per domain"
			backup_all_accounts_ldap_per_domain
		else
			backup_all_accounts_ldap_per_domain
		fi
	else
		if [ -z "$3" ]; then
			backup_all_accounts_ldap_per_domain $2
		else
			echo "Incorrect $@ params. Read --help."
			show_help
		fi
	fi

;;
* )
	echo "Incorrect parameters $@. See help."
	show_help
;;
esac
exit 0